package com.emapp.lccode.mode

import android.location.Location
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.Polygon
import com.amap.api.maps.model.Polyline
import com.emapp.lccode.base.BaseApplication
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.bean.DeviceKt
import com.emapp.lccode.bean.FeatureCollection
import com.emapp.lccode.bean.Geometry
import com.emapp.lccode.bean.MapJsonDeserialize
import com.emapp.lccode.bean.ProblemTypeKt
import com.emapp.lccode.bean.Project
import com.emapp.lccode.bean.SelectType
import com.emapp.lccode.bean.UpFileKt
import com.emapp.lccode.http.apiService
import com.emapp.lccode.utils.MmkvUtil
import com.emapp.lccode.utils.toJsonStr
import com.emapp.lccode.view.ProjectDeviceTypeDialog
import com.google.gson.GsonBuilder
import com.hjq.toast.Toaster
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.ext.requestNoCheck
import me.hgj.jetpackmvvm.state.ResultState
import java.util.concurrent.ConcurrentLinkedQueue

class ProjectViewModel : BaseViewModel() {
    var device: MutableLiveData<ResultState<ArrayList<DeviceKt>>> = MutableLiveData()
    var devicelist: MutableLiveData<ResultState<ArrayList<DeviceKt>>> = MutableLiveData()
    var deviceAdd: MutableLiveData<ResultState<Any>> = MutableLiveData()
    var projectList: MutableLiveData<ResultState<ArrayList<Project>>> = MutableLiveData()
    var file: MutableLiveData<ResultState<UpFileKt>> = MutableLiveData()
    var map_project: MutableLiveData<FeatureCollection> = MutableLiveData()
    var types: MutableLiveData<ArrayList<ProblemTypeKt>> = MutableLiveData()

    val typeDialog: ProjectDeviceTypeDialog by lazy { ProjectDeviceTypeDialog() }
    var selectType: SelectType = SelectType()
    var isFirstLoc = true
    var mylocation: Location? = null
    var guiji: ArrayList<LatLng> = arrayListOf()//轨迹
    var isRecordLine = false//正在录制轨迹
    var polyline: Polyline? = null//录制轨迹
    var polygons: ArrayList<Polygon> = arrayListOf()//项目区域
    var project_id = ""
    var keywords = ""
    var device_type = ""
    var  build_status = ""
    val polylineDataMap: MutableMap<String, DeviceKt> = HashMap()//存放设备（路）与地图polyline的绑定关系，点击路的时候用到
    //var markers: ArrayList<Marker> = arrayListOf()//设备图标
    val markers = ConcurrentLinkedQueue<Marker>()
    //var polylines: ArrayList<Polyline> = arrayListOf()//设备图标-路线
    var polylines= ConcurrentLinkedQueue<Polyline>() //地图显示的数据//
    private val TAG = this.javaClass.simpleName
    fun removeLine() {//清除录制轨迹
        polyline?.remove()
    }

    fun removeMarkers() {//清除设备
        markers.forEach { it.remove() }
    }

    fun removePolylines() {//清除设备
        polylines.forEach { it.remove() }
    }

    fun getDevice() {
        request(
            {
                apiService.getProjectDeviceMapList(
                    BaseApplication.instance.adminId,
                    project_id,
                    device_type,
                    build_status,
                    keywords
                )
            },
            devicelist,
            true
        )
    }

    /**
     * 项目列表
     */
    fun getUnFinishuProjectList(
        keywords: String = "",
        pager: Int = 0
    ) {
        val u = BaseApplication.instance.getUser() ?: return
        request({
            apiService.getUnFinishuProjectList(
                u.admin_id, keywords, BaseConfig.page_count.toString(), pager.toString()
            )
        }, projectList, false)
    }

    /**
     * 解析项目的json文件
     */
    fun jsonMap(path: String = "") {
        requestNoCheck({ apiService.getJsonMap(path) }, {
            val jsonString = it.string()
            val gson = GsonBuilder()
                .registerTypeAdapter(Geometry::class.java, MapJsonDeserialize())
                .create()
            val data = gson.fromJson(jsonString, FeatureCollection::class.java)
            map_project.postValue(data)
        }, {
            Toaster.show(it.errorMsg)
        }, false, "")
    }


    /**
     * 设备详情
     */
    fun getDeviceInfor(work_type: String, id: String) {
        request({
            apiService.getDeviceInfor(work_type, id)
        }, device, true)
    }

    fun getDeviceType(project_id: String) {
        val u = BaseApplication.instance.getUser() ?: return
        request({ apiService.getProjectDeviceType(project_id, u.admin_id) }, {
            types.postValue(it)
        }, {
            Toaster.show(it.errorMsg)
        }, true)
    }

    fun getDeviceAllType(pid: String) {
        request({ apiService.getDeviceType(pid) }, {
            viewModelScope.launch {
                withContext(Dispatchers.IO) {
                    MmkvUtil.setType(it.toJsonStr())
                }
            }
        }, {
            Toaster.show(it.errorMsg)
        }, false)
    }
    override fun onCleared() {
        super.onCleared()
        guiji.clear()
        isRecordLine = false
    }
}